import { TaskDefine } from "../Model/TaskDefine";

export default class TaskRecord {
    static getLastFinishTime() {
        return Guyu.storage.get("last_finish_time", null);
    }

    static recordLastFinishTime() {
        Guyu.storage.set("last_finish_time", String(Date.now()));
    }

    static loadLocalData(): TaskDefine.TaskStorageData {
        try {
            const data = Guyu.storage.get(TaskDefine.STORAGE_KEY);
            return data ? (JSON.parse(data) as TaskDefine.TaskStorageData) : {};
        } catch (error) {
            console.error('本地存储数据解析失败，重置为初始状态', error);
            return {};
        }
    }

    static saveLocalData(data: TaskDefine.TaskStorageData): void {
        Guyu.storage.set(TaskDefine.STORAGE_KEY, JSON.stringify(data));
    }

    static getTodayViewCount(taskId: string): number {
        const currentDate = this.toDayDate;
        const localData = this.loadLocalData();
        const taskRecord = localData[taskId];
        return taskRecord && taskRecord.date === currentDate ? taskRecord.finish_count : 0;
    }

    static getTaskStatus(taskId: string): { date: string; finish_count: number; total_count: number; finish_time?: string } | null {
        const localData = this.loadLocalData();
        const taskRecord = localData[taskId];
        return taskRecord || null;
    }

    static recordAdView(taskId: string, total_count: number, increment: number = 1): void {
        const currentDate = this.toDayDate;
        const localData = this.loadLocalData();
        let taskRecord = localData[taskId];

        if (!taskRecord || taskRecord.date !== currentDate) {
            // 初始化或更新任务记录
            taskRecord = { date: currentDate, total_count, finish_count: increment };
            localData[taskId] = taskRecord;
        } else {
            // 当天已有记录，累加次数
            if (taskRecord.finish_count >= taskRecord.total_count) {
                Guyu.Log.error('任务', taskId, '已完成，无法再记录');
                return;
            }
            taskRecord.finish_count = Math.max(taskRecord.finish_count + increment, 0); // 防止负数
        }

        // 检查是否完成任务
        if (!taskRecord.finish_time && taskRecord.finish_count >= taskRecord.total_count) {
            taskRecord.finish_time = Guyu.DayLite.now().format();
            Guyu.Log.debug('任务完成', taskId, '完成时间', taskRecord.finish_time);
        }

        Guyu.Log.debug('记录任务', taskId, '完成次数', taskRecord.finish_count);

        this.cleanOldRecords();
        this.saveLocalData(localData);
    }

    public static get toDayDate(): string {
        return Guyu.DayLite.now().format('YYYY-MM-DD')
    }

    public static cleanOldRecords(): void {
        const currentDate = this.toDayDate;
        const localData = this.loadLocalData();

        // 遍历所有任务，仅保留当天记录
        Object.keys(localData).forEach(taskId => {
            const taskRecord = localData[taskId];
            if (taskRecord.date !== currentDate) {
                // 非当天记录直接删除
                delete localData[taskId];
            }
        });
    }
}